<template>
  <div
    style="display: flex; flex-direction: column; width: 100%; margin-top: 25px"
  >
    <div
      style="
        margin-bottom: 10px;
        background: #eee;
        line-height: 40px;
        padding-left: 5px;
      "
    >
      基本信息
    </div>
    <p-form-model
      :labelCol="{ span: 8 }"
      :wrapperCol="{ span: 16 }"
      ref="ruleForm"
      :model="form"
      :rules="rules"
      style="margin-top: 20px"
    >
      <p-row :guter="20">
        <p-col :span="12">
          <p-form-model-item ref="number" label="单据编号" prop="number">
            <p-input v-model="form.number" disabled />
          </p-form-model-item>
        </p-col>
        <p-col :span="12">
          <p-form-model-item ref="source" label="来源单号" prop="source">
            <p-input v-model="form.source" :disabled="listData.isNewAdd" />
          </p-form-model-item>
        </p-col>
        <p-col :span="12">
          <p-form-model-item ref="producer" label="制单人" prop="producer">
            <p-input-search
              class="hideName"
              :disabled="listData.isNewAdd"
              v-model="form.producer.name"
              @search="onSearchDepUser('producer')"
            >
              <p-button slot="enterButton" :disabled="disabled"
                >选择用户</p-button
              >
            </p-input-search>
          </p-form-model-item>
        </p-col>
        <p-col :span="12">
          <p-form-model-item ref="date" label="制单日期" prop="date">
            <p-date-picker
              v-model="defauvalue"
              format="YYYY-MM-DD"
              @change="onChange"
              :disabled="listData.isNewAdd"
            />
          </p-form-model-item>
        </p-col>
        <p-col :span="12">
          <p-form-model-item ref="Company" label="更改单位" prop="Company">
            <p-select
              ref="Company"
              @change="handleChange"
              v-model="form.Company"
              :disabled="listData.isNewAdd"
            >
              <p-select-option :value="item.value" v-for="item in Company" :key="item.value">{{item.text}}</p-select-option>
            </p-select>
          </p-form-model-item>
        </p-col>
        <p-col :span="12">
          <p-form-model-item ref="type" label="更改类型" prop="type">
            <p-select v-model="form.type.text" :disabled="!listData.isNewAdd">
              <p-select-option
                @click="ValueChange(item)"
                :value="item.value"
                v-for="item in processChange"
                :key="item.value"
                >{{ item.text }}</p-select-option
              >
            </p-select>
          </p-form-model-item>
        </p-col>
        <p-col :span="12">
          <p-form-model-item ref="explain" label="更改来源说明" prop="explain">
            <p-input v-model="form.explain" :disabled="listData.isNewAdd" />
          </p-form-model-item>
        </p-col>
        <p-col :span="12">
          <p-form-model-item
            ref="Complete"
            label="更改物料齐套"
            prop="Complete"
          >
           <p-switch
              checked-children="是"
              un-checked-children="否"
              default-checked
              v-model="form.Complete"
              :disabled="listData.isNewAdd"
            />
          </p-form-model-item>
        </p-col>
        <p-col :span="12">
          <p-form-model-item
            ref="beforeNumber"
            label="更改前产品编码"
            prop="beforeNumber"
          >
            <p-input
              placeholder="请点击选择"
              v-model="form.beforeNumber"
              readonly
              @change="onChangeMaterialNo"
              ref="userNameInput"
              @click="openPop('before')"
              :disabled="listData.isNewAdd"
            >
              <p-icon slot="prefix" type="cluster" />
            </p-input>
          </p-form-model-item>
        </p-col>
        <p-col :span="12">
          <p-form-model-item
            ref="beforeName"
            label="更改前产品名称"
            prop="beforeName"
          >
            <p-input v-model="form.beforeName" :disabled="listData.isNewAdd" />
          </p-form-model-item>
        </p-col>
        <p-col :span="12">
          <p-form-model-item
            ref="afterNumber"
            label="更改后产品编码"
            prop="afterNumber"
          >
            <p-input
              placeholder="请点击选择"
              v-model="form.afterNumber"
              readonly
              ref="userNameInput"
              @click="openPop('after')"
              :disabled="listData.isNewAdd"
            >
              <p-icon slot="prefix" type="cluster" />
            </p-input>
          </p-form-model-item>
        </p-col>
        <p-col :span="12">
          <p-form-model-item
            ref="aftername"
            label="更改后产品名称"
            isTypeAprop="aftername"
          >
            <p-input
              v-model="form.afterName"
              :disabled="listData.isNewAdd || listData.isTypeA"
            />
          </p-form-model-item>
        </p-col>
        <p-col :span="8">
          <p-form-model-item ref="Planner" label="计划处理人" prop="PlannerName">
            <p-input-search
              class="hideName"
              :disabled="listData.isNewAdd"
              v-model="form.PlannerName"
              @search="onSearchDepUser('Planner')"
            >
              <p-button slot="enterButton" :disabled="disabled"
                >选择用户</p-button
              >
            </p-input-search>
          </p-form-model-item>
        </p-col>
        <p-col :span="8">
          <p-form-model-item
            ref="Craftsman"
            label="工艺处理人"
            prop="CraftsmanName"
          >
            <p-input-search
              class="hideName"
              :disabled="listData.isNewAdd"
              v-model="form.CraftsmanName"
              @search="onSearchDepUser('Craftsman')"
            >
              <p-button slot="enterButton" :disabled="disabled"
                >选择用户</p-button
              >
            </p-input-search>
          </p-form-model-item>
        </p-col>
        <p-col :span="8">
          <p-form-model-item ref="brand" label="品保处理人" prop="brandName">
            <p-input-search
              class="hideName"
              :disabled="listData.isNewAdd"
              v-model="form.brandName"
              @search="onSearchDepUser('brand')"
            >
              <p-button slot="enterButton" :disabled="disabled"
                >选择用户</p-button
              >
            </p-input-search>
          </p-form-model-item>
        </p-col>
       <p-col :span="8">
          <p-form-model-item ref="main" label="工艺主管" prop="mainName">
              <p-input-search
              class="hideName"
              :disabled="listData.isNewAdd"
              v-model="form.mainName"
              @search="onSearchDepUser('main')">
              <p-button slot="enterButton" :disabled="disabled">选择用户</p-button>
              </p-input-search>
          </p-form-model-item>
      </p-col>
        <p-col :span="8">
          <p-form-model-item ref="manager" label="工艺经理" prop="managerName">
              <p-input-search
              class="hideName"
              :disabled="listData.isNewAdd"
              v-hide="changemanager"
              v-model="form.managerName"
              @search="onSearchDepUser('manager')"> 
              <p-button slot="enterButton"  :disabled="disabled">选择用户</p-button>
              </p-input-search>
          </p-form-model-item>
      </p-col>

      <p-col :span="8">
          <p-form-model-item
            ref="Craftsman"
            label="产品更改范围"
            >
            <p-div>
              <a href="javascript:;" @click="lockdetails">产品锁定单号明细</a>
            </p-div>
          </p-form-model-item>
        </p-col>

        <p-col :span="24">
          <p-form-model-item
            ref="Craftsman"
            label="产品更改内容"
            :labelCol="{ span: 3 }"
          >
            <p-select
              mode="multiple"
              style="width: 100%"
              @change="handleChange"
              v-model="form.list"
            >
              <p-select-option
                :value="item.value"
                name="type"
                v-for="item in list"
                :key="item.value"
                >{{ item.text }}
              </p-select-option>
            </p-select>
          </p-form-model-item>
        </p-col>

        
      </p-row>
    </p-form-model>

    <PageTitle>工艺路线编排</PageTitle>
    <p-tabs :activeKey="showCard" @change="changeCard">
      <p-tab-pane key="1" tab="工单1工艺路线">
        <p-row>
          <p-col :span="24">
            <p-form-model-item
              ref="Craftsman"
              label="工艺路线"
              :labelCol="{ span: 3 }"
            >
              <a href="javascript:;" @click="handletemporary"
                >临时BOM物料分配表</a
              >
            </p-form-model-item>
          </p-col>
        </p-row>
        <p-skeleton :loading="!showFlag" active />
        <drawRoute :pdata="pData" v-show="showFlag" ref="DrawRoute" />
      </p-tab-pane>
      <p-tab-pane key="2" tab="工单2工艺路线">
        <p-row>
          <p-col :span="24">
            <p-form-model-item
              ref="Craftsman"
              label="工艺路线"
              :labelCol="{ span: 3 }"
            >
              <a href="javascript:;" @click="handletemporary"
                >临时BOM物料分配表</a
              >
            </p-form-model-item>
          </p-col>
        </p-row>
        <p-skeleton :loading="!showFlag" active />
        <drawRoute :pdata="pData" v-show="showFlag" :ref="'DrawRoute' + 1" />
      </p-tab-pane>
      <p-tab-pane key="3" tab="工单3工艺路线">
        <p-row>
          <p-col :span="24">
            <p-form-model-item
              ref="Craftsman"
              label="工艺路线"
              :labelCol="{ span: 3 }"
            >
              <a href="javascript:;" @click="handletemporary"
                >临时BOM物料分配表</a
              >
            </p-form-model-item>
          </p-col>
        </p-row>
        <p-skeleton :loading="!showFlag" active />
        <drawRoute :pdata="pData" v-show="showFlag" ref="DrawRoute" />
      </p-tab-pane>
    </p-tabs>

    <div v-show="isStatus">
          <div class="table-operator" style="text-align:right;margin-top:20px" v-show="this.listData.Approval">
            <p-button @click="saveButton" type="primary" :loading="btnLoading">保存</p-button>
            <p-button @click="submitButton" type="primary" :loading="btnLoading">提交</p-button>
        </div>
        <div class="table-operator" style="text-align:right;margin-top:20px" v-show="!this.listData.Approval">
            <p-button @click="confirm" type="primary" :loading="btnLoading">确认</p-button>
            <p-button @click="reject" type="primary" :loading="btnLoading">驳回</p-button>
        </div>
    </div>
    <!-- 临时BOM物料分配表 -->
    <p-modal v-model="temporaryVisible" title @ok="temporaryOk" width="70%">
      <temporary></temporary>
    </p-modal>
    <!-- 产品锁定明细 -->
    <p-modal v-model="lockdetailsVisible" title @ok="lockdetailsOk" width="70%">
      <lockdetails></lockdetails>
    </p-modal>
    <!-- 产品编码列表 -->
    <p-modal
      v-model="nulberListVisible"
      title
      @ok="nulberListVisibleOk"
      width="70%"
    >
      <nulberListVisible @getNumber="getlist"></nulberListVisible>
    </p-modal>

    <!-- 人员选择模块 -->
    <j-select-user-by-dep-modal
      :ObjectList="ObjectList"
      ref="selectModal"
      :modal-width="1250"
      :multi="true"
      @ok="selectOK"
      @getName="getName"
      :user-ids="value"
      @initComp="initComp"
    />
  </div>
</template>
<script>
import Vue from "vue";
import PageTitle from "@/components/PageTitle";
import drawRoute from "./handlePocess/drawRoute";
import { ajaxGetDictItems } from "@/api/api";
import temporary from "./temporary";
import lockdetails from "./Lockdetails";
import JSelectUserByDepModal from "./JSelectUserByDepModal";
import nulberListVisible from "./nulberListVisible";
import moment from "moment";
import {
  httpAction,
  postAction,
  getAction,
  putAction,
  api,
} from "@/api/manage";

export default {
  inject: ["userInfo"],
  components: {
    PageTitle,
    drawRoute,
    temporary,
    lockdetails,
    JSelectUserByDepModal,
    nulberListVisible,
  },
  props: {
    listData: {
      type: Object,
      required: false,
    },
  },
  data() {
    return {
      moment,
      peo: "",
      showCard: 1,
      list: [], //产品内容更改
      InventoryPackaging: [], //包材保留
      processChange: [], //更改类型
      Company:[],
      btnLoading:false,
      isStatus:true,
      temporaryVisible: false,
      changedetailsVisible: false,
      lockdetailsVisible: false,
      nulberListVisible: false,
      showFlag: false,
      changeNumber: "",
      defauvalue: moment(new Date(), "YYYY-MM-DD"),
      idGetInfo: {},
      form: {
        type: {},
        producer: {},
        Planner: {},
        Craftsman: [],
        brand: {},
        before: {},
        after: {},
        main:{},
        manager:{},
        beforeNumber: "",
        beforeName: "",
        afterNumber: "",
        afterName: "",
        PlannerName:'',
        CraftsmanName:'',
        brandName:'',
        mainName:'',
        managerName:'',
        Complete: false,
        updata: false,
      },
      rules: {
        number: [{ required: true, message: "请填写单据编号", trigger: "blur" },],
        source: [{ required: true, message: "请填写来源单号", trigger: "blur" },],
        producer: [{ required: true, message: "请填写制单人", trigger: "blur" },],
        Company: [{ required: true, message: "请填写更改单位", trigger: "blur" },],
        type: [ { required: true, message: "请选择更改类型", trigger: "change" },],
        explain: [{ required: true, message: "请填写更改来源说明", trigger: "blur" },],
        beforeNumber: [{ required: true, message: "请填写更改前产品编码",trigger: "change",},],
        beforeName: [{ required: true, message: "请填写更改前产品名称", trigger: "blur" },],
        afterNumber: [ {required: true,message: "请填写更改后产品编码", trigger: "change"},],
        afterName: [ { required: true, message: "请填写更改后产品名称" },],
        aftername: [{ required: true, message: "请填写更改后产品名称", trigger: "blur" },],
        PlannerName: [ { required: true, message: "请填写计划处理人", trigger: "blur" },],
        CraftsmanName: [{ required: true, message: "请填写工艺处理人", trigger: "blur" },],
        Material: [{ required: true, message: "请选择包材保留", trigger: "change" },],
        brand: [{ required: true, message: "请选择包材保留", trigger: "change" }, ],
        brandName: [{ required: true, message: "请填写品保处理人" }],
        managerName: [{ required: true, message: "请填写工艺经理" }],
        mainName: [{ required: true, message: "请填写工艺主管" }],
      },
      url: {
        number:
          "/mes-manufacture/mfHalfProductInStorage/getProcessInfoForHalfProduct", //根据产品编码获取生产工单号
        getWorkOrder: "/mes-craft/craft/mesPeBill/getRouterContentByOrderNums",
        save: "/mes-craft/craft/mesPeBill", //"新增返工单"
      },
    };
  },
  computed: {
    handle() {
      return this.$route.query.handle;
    },
  },
  mounted() {
    this.lodacontent();
    if(this.listData.billStatus==6){this.isStatus=false}
    this.form.type = this.listData.typeChange;
    this.loadForm()
  },
  watch: {
    listData() {
      this.form.type = this.listData.typeChange;
    },
  },
  methods: {
    changeCard(a) {
      this.showCard = a;
    },
    querylist() {
      if (this.listData.hand == "change") {
        let arr = this.listData.productChangeContent.split(",");
        let array = [];
        arr.forEach((item) => {
          array.push(
            this.list.filter((items) => {
              return items.value == item;
            })[0].value
          );
        });
        this.form.list = array;
      }
    },
    getlist(data) {
      if (this.changeNumber == "before") {
        this.form.beforeNumber = data[0].mcode;
        this.form.beforeName = data[0].mname;
      } else if (this.changeNumber == "after") {
        this.form.afterNumber = data[0].mcode;
        this.form.afterName = data[0].mname;
      }
    },
    //   判断新增生成单据编号
    ifADD() {
      if (this.listData.isNewAdd == false) {
        let param = {
          commonFormData: {},
          rules: [
            { ruleCode: "mes_ReturnDocument", columnName: "labelTemplateNo" },
          ],
        };
        putAction(api.ruleBaseURL, param).then((res) => {
          // 执行成功，获取返回的值，并赋到页面上
          if (res.code == 0) {
            this.$set(this.form, "number", res.data.labelTemplateNo);
          }
        });
      }
    },
    loadForm() {
        if (this.listData.hand == "add") {
          this.getnewDate();
          this.form.producer = {
            name: this.userInfo.empname,
            uid: this.userInfo.empno,
          };
          this.ifADD();
        } else if (this.listData.hand = "change") {
          this.setFormData(this.listData);
          this.nulberListVisibleOk();
        }
    },
    // 根据数据赋值给表单
    setFormData(data) {
      console.log(data);
      this.form.number = data.billNum;
      this.$set(this.form, "source", data.billOriNum);
      this.$set(this.form, "explain", data.productChangeExplain);
      this.$set(this, "defauvalue", moment(data.createTime, "YYYY-MM-DD"));

      this.form.producer.uid = data.billCreate;
      this.form.producer.name = data.billCreateName;
      this.form.Company = data.changeCompany;
      this.form.Complete = data.changeMaterialSet == "false" ? false : true;
      this.form.beforeNumber = data.productCodeChangeBefore;
      this.form.beforeName = data.productCodeChangeBeforeName;
      this.form.afterNumber = data.productCodeChangeAfter;
      this.form.afterName = data.productCodeChangeAfterName;
      this.form.plan.uid = data.planProcessor;
      this.form.plan.name = data.planProcessorName;
      this.form.Craftsman.uid = data.processProcessor;
      this.form.main.uid=data.processSupervisor,
      this.form.main.name=data.processSupervisorName,
      this.form.manager.uid=data.processManager
      this.form.manager.name=data.processManagerName
    },

    saveButton() {

      if (!this.listData.isNewAdd) {
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
              if (this.listData.hand == "add") {
                this.btnLoading = true;
                console.log(this.url.save)
                postAction(this.url.save, this.getObj(0)).then((res) => {
                  console.log('在请求')
                  if (res.code == 0) {
                    this.$message.success("保存成功");
                    this.btnLoading = false;
                    this.$emit("closeonlineRework");
                  } else {
                    this.$message.error(res.msg);
                  }
                });
              } else if (this.listData.hand == "change") {
                this.btnLoading = true;
                 console.log('该提交')
                putAction(this.url.save, this.getObj(0, this.listData.id)).then(
                  (res) => {
                    if (res.code == 0) {
                      this.$message.success("修改成功");
                    this.btnLoading = false;
                      this.$emit("closeonlineRework");
                    } else {
                      this.$message.error(res.msg);
                    }
                  }
                );
              }
          }
        });
      }
    },
    submitButton() {
      if (!this.listData.isNewAdd) {
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            if (this.form.beforeNumber) {
              postAction(this.url.save, this.getObj(1)).then((res) => {
                if (res.code == 0) {
                  this.$message.success("提交成功");
                  this.$emit("closeretentionVisible");
                } else {
                  this.$message.error(res.msg);
                }
              });
            } else {
              this.$message.warning("请先选择产品编码");
            }
          }
        });
      }
    },

    handletemporary() {
      if (this.form.beforeNumber) {
        this.temporaryVisible = true;
      } else {
        this.$message.warning("请先选择产品编码");
      }
    },
    nulberListVisibleOk() {
      if (this.changeNumber == "after") {
        this.getRout();
      }
      this.nulberListVisible = false;
    },
    // 封装获取工艺路线函数
    // 根据产品编码获取工艺路线编码，版本
    getRout(obj) {
      this.showFlag = false;
      // postAction(this.url.number, { productCode: this.form.afterNumber }).then(
      //   (res) => {
      //     if (res.code == 0) {
      //       let obj = {
      //         processBillNo: res.data.processBillNo,
      //         billNum: this.form.number,
      //       };
      //       new Promise((resolve) => {
      //         postAction(this.url.getWorkOrder, obj).then((res) => {
      //           if (res.code == 0) {
      //             resolve(res.data);
      //           } else {
      //             this.$message.error(res.msg);
      //           }
      //         });
      //       }).then((res) => {
      //         this.pdata = res.data;
      //         this.showFlag = true;
      //       });
      //     }
      //   }
      // );

      // this.showFlag = false;
      // postAction(this.url.getRouter, obj).then((res) => {
      //   if (res.code == 0) {
      //     this.routerCode = res.data.routerCode;
      //     this.version = res.data.routerVersion;
      //     this.getRoute(this);
      //   } else {
      //     this.$message.error(res.msg);
      //   }
      // });
      // this.nulberListVisible = false;
    },

    openPop(data) {
      this.changeNumber = data;
      this.nulberListVisible = true;
    },
    onSearchDepUser(value) {
      this.$refs.selectModal.showModal();
      this.peo = value;
    },
    onChange(data, str) {
      this.form.data = str;
    },
    getnewDate() {
      this.form.data = moment(new Date()).format("YYYY-MM-DD");
    },
    // 根据工艺路线编码，版本，获取工艺路线
    // getRoute(that) {
    //   new Promise((resolve) => {
    //     mesPeProcess
    //       .getRouter({ routerCode: this.routerCode, version: this.version })
    //       .then((res) => {
    //         if (res.code === 0) {
    //           resolve(res.data);
    //         } else {
    //           this.$message.warning(res.msg);
    //           this.$message.error(res.msg);
    //         }
    //       });
    //   }).then((res) => {
    //     this.showFlag = true;
    //     this.pdata = res;
    //   });
    // },
    //   加载数据字典
    lodacontent() {
      Promise.all([
        new Promise(resolve=>{
          ajaxGetDictItems("InventoryChanges").then((res) => {
            if (res.code == 0) {
              resolve(res.data)
            } else {
              this.$message.error(res.msg);
            }
          });
        }),
        new Promise(resolve=>{
          ajaxGetDictItems("processChange").then((res) => {
            if (res.code == 0) {
              resolve(res.data)
            } else {
              this.$message.error(res.msg);
            }
          });
        }),
        new Promise(resolve=>{
            ajaxGetDictItems("mes_change_Company").then((res) => {
            if (res.code == 0) {
              resolve(res.data)
            } else {
              this.$message.error(res.msg);
            }
          });
        }),
      ]).then(res=>{
        this.list = res[0];
        this.processChange = res[1];
        this.Company=res[2];
        this.querylist()
      })
      
      
      
    },

    handletemporary() {
      this.temporaryVisible = true;
    },
    lockdetails() {
      this.lockdetailsVisible = true;
    },
    temporaryOk() {
      this.temporaryVisible = false;
    },
    lockdetailsOk() {
      this.lockdetailsVisible = false;
    },
    onSearchDepUser(value) {
      this.$refs.selectModal.showModal();
      this.peo = value;
    },
    onChange(data, str) {
      this.form.data = str;
    },
    getnewDate() {
      this.form.data = moment(new Date()).format("YYYY-MM-DD");
    },
    selectOK(rows, idstr) {
      if (this.peo == "producer") {
        this.form.producer = rows;
      } else if (this.peo == "Planner") {
        this.form.Planner = rows;
        this.form.PlannerName = rows.name;
      } else if (this.peo == "manager") {
        this.form.manager = rows;
        this.form.managerName = rows.name;
      } else if (this.peo == "main") {
        this.form.main = rows;
        this.form.mainName = rows.name;
      }else if (this.peo == "Craftsman") {
         this.form.Craftsman = rows;
        this.form.CraftsmanName = rows.name;
    }else if(this.peo=="brand"){
       this.form.brand = rows;
        this.form.brandName = rows.name;
    }
    },
    // 获取接口所需参数
    getObj(data, listid) {
      return {
        billNum: this.form.number, //单据号
        billOriNum: this.form.source, //来源单号
        billCreate: this.form.producer.uid, //制单人
        billCreateName: this.form.producer.name, //制单人名称
        changeCompany: this.form.Company, //更改单位
        changeType: this.form.type.value.toString(), //更改类型
        productChangeExplain: this.form.explain, //更改来源说明
        changeMaterialSet: this.form.Complete.toString(), //是否齐套
        productCodeChangeBefore: this.form.beforeNumber, //更改前编码
        productCodeChangeAfter: this.form.afterNumber, //更改后编码
        planProcessor: this.form.Planner.uid, //计划处理人
        planProcessorName: this.form.PlannerName, //计划处理人名称
        processProcessor: this.form.Craftsman.uid, //工艺处理人
        productChangeContent: this.form.list.toString(), //产品更改内容
        pcbaUpgrade: this.form.updata.toString(), //硬件升级
        produceOder: this.form.code, //生产订单号
        qualityProcessor:this.form.brand.uid,//品保处理人工号
        qualityProcessorName:this.form.brandName, //品保处理人名称
        processSupervisor:this.form.main.uid,
        processSupervisorName:this.form.mainName,
        processManager:this.form.manager.uid,
        processManagerName:this.form.managerName,
        billStatus: data,
        id: listid,
      };
    },
 
  },
};
</script>
<style  scoped>
.poros-form .poros-form-item {
  height: 44px;
}
</style>